<template>
    <div style="height: 100%;" class="edit-form">
        <div class="handler-box">
            <div class="operation-left">
              <el-button class="custome-btn" :type="item.type" :size="item.size" :disabled="item.disabled" :plain="item.plain" v-for="item in actionBarList" :key="item.uuid" @click="actionBarClick(item)">{{ item.columnName }}</el-button>
            </div>
            <div class="operation-right">
                <el-button class="custome-btn" :type="item.type" :size="item.size" :disabled="item.disabled"  v-show="item.visibility"  :plain="item.plain" v-for="item in batchActionBarList" :key="item.uuid" @click="actionBarClick(item)">{{ item.columnName }}</el-button>
            </div>
        </div>
        <el-table v-bind="heightConfig" size="mini" :stripe="activeData.stripe" :data="tableData" :border="activeData.border"
        :header-cell-style="{ backgroundColor: activeData.headerColor,color:activeData.fontColor }"
        style="width: 100%" :key="renderKey"
          @selection-change="handleSelectionChange"
        >
        <el-table-column
                v-if="activeData.multiple"
                type="selection"
                align="center"
                width="55">
            </el-table-column>
            <el-table-column
                v-if="activeData.index"
                type="index"
                label="序号"
                align="center"
                width="50">
                </el-table-column>

            <el-table-column v-for="item in columnLists" :key="item.uuid" :label="item.columnName" :width="item.width?item.width:''" align="center">
                <template slot="header" >
                 <span :class="item.required?'required-txt':''"> {{ item.columnName }}</span>
                </template>
                <template slot-scope="scope">

                    <div class="row-item"  v-if="scope.row.editable">
                        <span v-if="item.renderType == 'text'">
                            {{ scope.row[item.field] }}
                        </span>
                        <el-input type="text" v-model="scope.row[item.field]" v-if="item.renderType == 'input'"
                            :disabled="item.disabled" :readonly="item.readonly"></el-input>
                        <el-select type="text" style="width: 100%;" class="select-box" v-model="scope.row[item.field]"
                            v-if="
                                item.renderType == 'select'
                            " :disabled="item.disabled" :readonly="item.readonly" filterable>
                            <el-option :label="m[item.apiLabel||'label']" :value="m[item.apiValue||'value']" v-for="(m,n) in item.options" :key="n">
                                <div class="option-li-box"  >
                                    <div class="option-li" @click="selectChange(m,scope.row,item)" style="z-index:23">

                                        <span style="float: left">{{ m[item.apiLabel] }}</span>
                                        <span style="float: right; color: #8492a6; font-size: 13px" v-if="item.assistValue">{{ m[item.assistValue] }}</span>
                                    </div>
                                </div>
                            </el-option>
                        </el-select>
                        <el-date-picker style="width: 100%;" v-if="item.renderType == 'date'"
                            v-model="scope.row[item.field]" :disabled="item.disabled" :readonly="item.readonly"
                            :type="item.dateType"></el-date-picker>
                        <el-time-picker style="width: 100%;" v-if="item.renderType == 'time'"
                            v-model="scope.row[item.field]" :disabled="item.disabled" :readonly="item.readonly"
                            placeholder="选择时间"></el-time-picker>
                    </div>
                    <div class="row-item" v-else> {{ scope.row[item.field] }}</div>
                </template>
            </el-table-column>
            <el-table-column label="操作" v-if="activeData.operationBar.isOperation" :width="activeData.operationBar.width" align="center"  :fixed="activeData.operationBar.isFixed?'right':false">
                <template slot-scope="scope">
                  <div class="btn-box">
                    <div class="row-btn" v-for="m in operationBtnLists" :key="m.uuid" :disabled="m.disabled" v-show="isShowBtn(scope.row,m)"  @click="actionRowClick(m,scope.row,scope.$index)">
                        {{ m.columnName }}
                    </div>
                  </div>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-page" v-if="activeData.pagination">
            <el-pagination
                @current-change="currentChange"
                :current-page.sync="page.page"
                :page-size="page.size"
                layout="total, prev, pager, next"
                :total="page.total">
            </el-pagination>
        </div>
    </div>
</template>

<script>

export default {
    name: 'editableForm',
    props:{
        activeData:Object,
        page:{
            type:Object,
            default(){
                return {
                    total:0,
                    size:10,
                    page:1
                }
            }
        }
    },
    data() {
        return {
            renderKey:1233334,
            tableData: [

            ],
            columnLists: [],
            operationBtnLists:[],
            actionBarList:[],
            batchActionBarList:[],
            multipleSelection:[], // 批量选择
            heightConfig:{}
        }
    },
    computed: {

    },
    watch: {
        'activeData': {
            handler(newv) {
                if (!newv) { return }
                this.setColumnLists()
                this.setOperationBtnLists()
                this.setActionBar('actionBarList')
                this.setActionBar('batchActionBarList')
                this.setTableHeight(newv)
                this.renderKey = new Date().getTime()

            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        judgTableRequired(){ // 判断表格必填
            let tmps = this.columnLists.filter((el)=>{
                return el.required
            })
            let obj = {}
            for(var i=0;i < tmps.length;i++){
                for(var j =0;j < this.tableData.length;j++){
                    let row = this.tableData[j]
                    if(!(tmps[i].field&&row[tmps[i].field])){
                        obj.columnName = tmps[i].columnName
                        obj.index = j+1
                        break;
                    }
                }
            }
            if(Object.keys(obj).length!=0){
                    this.$message.error(`表格第${obj.index}行${obj.columnName}必填`)
                    return false
            }
            return true
        },
        setEditable(row,mark){ // 设置表单是否可编辑
            row.editable = mark||true
        },
        isShowBtn(row,item){
            if(item.editableName){
                return row[item.editableName]?item.editable:(!item.editable)
            }else{
                return true
            }
        },
        setTableHeight(newv){
            if(newv.height&&newv.height!='100%'){
                this.heightConfig ={
                    height:newv.height
                }
            }else{
                this.heightConfig = {}
            }

        },
        getTableData(){ // 获取表格数据
            return this.tableData
        },
        setTableData(lists){ // 设置表格数据
            if(lists&&Array.isArray(lists)){
                lists.forEach((el)=>{
                    el.uuid = this.generateRandomNums()
                    el.editable = false
                })
                this.tableData = lists
            }

        },
       generateRandomNums(){
        var time = new Date().getTime()
        const randomNum = Math.floor(Math.random() * 900) + 100
        let num = (time + "" + randomNum)*1
        return num
        },
        setColumnLists() {
            this.columnLists = this.activeData.columnLists || []

        },
        setOperationBtnLists(){
            this.operationBtnLists = this.activeData.operationBtnLists || []
        },
        setActionBar(bar){
            if(!bar){return}
            this[bar] =  this.activeData[bar]
        },
        actionBarClick(item){
            item.func&&this[item.func]&&this[item.func]()
            
            this.$emit('actionBatchClick',this.multipleSelection)
        },
        async actionRowClick(item,row,index){
            if(item.func&&this[item.func]){
                await this[item.func](row,item,index)
                this.$emit('actionRowClick',item,row,index)
            }else{
                this.$emit('actionRowClick',item,row,index)
            }
        },
        addRow(){
        
           this.tableData.push({
                uuid:this.generateRandomNums(),
                editable:true
           })
           this.$emit('addRow')
        },
        editRow(row,item,index){
            row.editable = true
        },
        deleteRow(row,item,index){
            return new Promise((resolve,reject)=>{
                this.$confirm('请确认是否删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.tableData.splice(index,1)
                    resolve()
                }).catch(() => {
                    reject()
                });
            })

        },
        saveRow(row,item,index){
            row.editable = false
            return new Promise((resolve,reject)=>{
                let tmps = this.columnLists.filter((el)=>{
                    return el.required
                })
                let obj = {}
                for(var i=0;i < tmps.length;i++){
                    if(!(tmps[i].field&&row[tmps[i].field])){
                        obj.columnName = tmps[i].columnName
                        break;
                    }
                }
                if(Object.keys(obj).length!=0){
                    this.$message.error(`第${index+1}行${obj.columnName}必填`)
                    return
                }
                resolve()
            })
        },
        batchDelete(){

        },
        currentChange(val){
            this.$emit('currentChange',val)
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        selectChange(item,row,configItem){
            this.$emit('selectChange',item,row,configItem)
        }
    }
}
</script>

<style scoped lang='scss'>
.edit-form{
    width:100%;
    height: 100%;
}
.required-txt{
    position: relative;
    &::after{
        content: "*";
        position: absolute;
        color: rgb(249, 11, 11);
        
    }
}
.btn-box{
    display: flex;
    justify-content: center;
}
.row-btn{
    color:#5584ff;
    padding: 4px;
    cursor: pointer;

    &:hover{
        color: #054bfd;
        font-weight: 600;
    }
}
.handler-box{
    display: flex;
    justify-content: space-between;
    padding: 10px;
}
.pagination-page{
    padding: 5px 0px;
    display: flex;
    flex-direction: row-reverse;
}
.option-li-box{
    height: 34px;
    position: relative;
    .option-li{
        position: absolute;
        left: -20px;
        padding: 0px 20px;
        right: -20px;
        box-sizing: border-box;
        z-index:2

    }
}


</style>
